const win = (window as any).win;

export interface IWinStatus {
  isMaximized: boolean;
  isMinimized: boolean;
  normalWidth: number;
  normalHeight: number;
  normalX: number;
  normalY: number;
  width: number;
  height: number;
}

const status: IWinStatus = {
  isMaximized: false,
  isMinimized: false,
  normalX: win.getPositionX(),
  normalY: win.getPositionY(),
  normalWidth: win.getWidth(),
  normalHeight: win.getHeight(),
  width: win.getWidth(),
  height: win.getHeight(),
};

const statusListeners: ((s: IWinStatus) => void)[] = [];

export function getWinStatus (): IWinStatus {
  return status;
}

export function winIsMaximized (): boolean {
  return status.isMaximized;
}

export function winIsMinimized (): boolean {
  return status.isMinimized;
}

export function winClose () {
  win.close();
}

export function winUnmaximize () {
  status.isMaximized = false;
  win.setResizable(true);
  win.resize(status.normalX, status.normalY, status.normalWidth, status.normalHeight);
  setTimeout(() => {
    callListeners();
  }, 0);
}

export function winMaximize () {
  status.isMaximized = true;
  win.setResizable(false);
  win.maximize();
  setTimeout(() => {
    callListeners();
  }, 0);
}

export function onStatusChanged (cb: (s: IWinStatus) => void) {
  statusListeners.push(cb);
}

export function winMinimize () {
  status.isMinimized = true;
  win.minimize();
  setTimeout(() => {
    callListeners();
  }, 0);
}

function callListeners () {
  status.width = win.getWidth();
  status.height = win.getHeight();
  statusListeners.forEach(cb => {
    try {
      cb(status);
    } catch (e) {
      console.error(e);
    }
  });
}

win.on('maximize', () => {
  status.isMaximized = true;
  callListeners();
});

win.on('unmaximize', () => {
  status.isMaximized = false;
  callListeners();
});

win.on('minimize', () => {
  status.isMinimized = true;
  callListeners();
});

win.on('restore', () => {
  status.isMinimized = false;
  callListeners();
});

win.on('resize', () => {
  if (!status.isMaximized) {
    status.normalWidth = win.getWidth();
    status.normalHeight = win.getHeight();
    status.normalX = win.getPositionX();
    status.normalY = win.getPositionY();
  }
  callListeners();
});
